package idv.arthur.work.validation;

import idv.arthur.work.Widgets;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckEnvSeq extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CheckEnvSeq() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ResultSet rs2 = null;
		String errPars = "}";
		final String bssId = "MBMS";
		String res = "notOK";
		
		int deliverSN = Integer.parseInt(request.getParameter("deliverSN"));
		
		String envid = request.getParameter("envid");
		String depTar = request.getParameter("depTar");

		String[] dt = depTar.split(",");

		String strSQL = "";
		try {
			conn = wid.getConn(true);
			/*	檢查子系統	是否皆存在	*/
			strSQL = "SELECT COUNT(*) FROM subsys WHERE bssid=? AND subsysid=?";
			
			String lackedSubSys = "";
			
			for (int i =0;i<dt.length;i++) {
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, bssId);
				ps.setString(2, dt[i]);
				rs = ps.executeQuery();
				rs.next();
				if ( rs.getInt(1) != 1 ) {
					lackedSubSys += (dt[i] + ","); // 缺少這些子系統	
				}
			}

			if (!"".equalsIgnoreCase(lackedSubSys)) {	//有值表示有缺少子系統設定
				res = "缺少下列子系統設定：\n" + lackedSubSys + "\n請先完成設定";
			} else {
				/*	檢查子系統下的環境	是否皆存在	*/
				strSQL = "SELECT COUNT(envid) FROM env WHERE envid = ? AND subsysid = ? AND bssid = ?";
				String lackedEnv = "";

				for (int i =0;i<dt.length;i++) {
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, envid);
					ps.setString(2, dt[i]);
					ps.setString(3, bssId);
					rs = ps.executeQuery();
					rs.next();
					if ( rs.getInt(1) != 1 ) {
						lackedEnv += (dt[i] + ",");	//缺少該子系統下，此種環境的設定	
					}
				}
				
				if (!"".equalsIgnoreCase(lackedEnv)) {	//有值表示有缺少環境設定
					res = "缺少下列環境設定：\n" + lackedEnv + "\n請先完成設定";;
				} else {
					/*	檢查環境的部署順序	*/
					int preClass = 0;
					
					String preDep = "";
					for (int i =0;i<dt.length;i++) {
						strSQL = "SELECT envid,envname, preClass FROM env WHERE envid = ? AND subsysid = ? AND bssid = ?";
						ps = conn.prepareStatement(strSQL);
						ps.setString(1, envid);
						ps.setString(2, dt[i]);
						ps.setString(3, bssId);
						rs = ps.executeQuery();
						rs.next();
						preClass = rs.getString("preClass")==null?0:rs.getInt("preClass");
						if (preClass != 0 ) {	//表示有部署順序限制
							/*
							 *		1. 將有順序的那些環境都找出來
							 *		2.	這些環境都要去查 【各項目主機部署記錄】，看該【部署記畫】，是否有部署過那些 環境 的記錄
							 * */
							
							strSQL = "SELECT envid,envname FROM env WHERE selfClass=? AND bssid=? AND subsysid=?";
							ps = conn.prepareStatement(strSQL);
							ps.setInt(1, preClass);
							ps.setString(2, bssId);
							ps.setString(3, dt[i]);
							rs = ps.executeQuery();
							
							strSQL = "SELECT COUNT(*) FROM itemdeplog t1, depmain t2,deplmain t3, deltask t4, depdetail t5 WHERE t2.deplmainSN = t3.deplmainSN AND t1.depmainSN=t2.depmainSN AND t5.depmainSN=t2.depmainSN AND t4.deplmainSN=t3.deplmainSN AND t4.deliverySN=? AND t1.bssid=? AND t1.subsysid=? AND t1.envid=?";
							while (rs.next()) {
								ps = conn.prepareStatement(strSQL);
								ps.setInt(1, deliverSN);
								ps.setString(2, bssId);
								ps.setString(3,dt[i]);
								ps.setString(4, rs.getString("envid"));
								rs2 = ps.executeQuery();
								rs2.next();
								
								if (rs2.getInt(1) ==0) {
									preDep += ( wid.DB2UI( rs.getString("envname"),conn.getMetaData().getDatabaseProductName() )+"( "+rs.getString("envid")+ " )");
								}
							}
						}
					}
					
					if ("".equalsIgnoreCase(preDep)) {	//表示該部署的都部署了
						res = "可以部署了!!";
					} else {
						res = "需要先部署下列環境：\n" + preDep + "\n";;
					}
				}
			}
		}  catch ( UnsupportedEncodingException e ) {
			res =	wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch ( SQLException e) {
			res =	wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch ( Exception e) {
			res =	wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (rs2 != null) {rs2.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		response.getWriter().write(res);
	}
}